<?php

namespace App\Services;

use App\Repositories\ThirdRepo;
use App\Repositories\UserRepo;
use EasyWeChat\Foundation\Application;
use App\Services\JwtService;
class WechatService
{

	public static $easyWechat = null;

	public static function getApp()
	{
		$options = [
			 'mini_program' => [
        	 	'app_id'   => 'wxb54801f1df727b68',
        	 	'secret'   => 'a80fec3fca162de70ba2a33604926106',
        	 	'token'    => 'token',
        	 	'aes_key'  => 'component-aes-key'
       	 	],
		];
		if(self::$easyWechat != null && (self::$easyWechat instanceof Application )) {
			return self::$easyWechat;
		} else {
			$app = new Application($options);
			// var_dump($app);
			if($app) {
				self::$easyWechat = $app;
			} else {
				throw new InvalidException("请检查小程序配置");
			}
			return self::$easyWechat;
		}
		
	} 
	public function login($code,$nick_name="",$avatar_url="")
	{
		$app = self::getApp();
		$miniProgram = $app->mini_program;
		if(!$miniProgram) {
			throw new InvalidException("对象失败");
		}
		$sessionKey = $miniProgram->sns->getSessionKey($code);
		if(!$sessionKey) {

			throw new InvalidException("获取sessionKey失败");
		}
		$data = $sessionKey->toArray();
		return  $this->loginOrRegister($data['openid'],$nick_name,$avatar_url);

	}
	//判断是否注册，如果已注册就返回
	public function loginOrRegister($openid,$nick_name,$avatar_url)
	{
		$thirdRepo =  new ThirdRepo();

		$third = $thirdRepo->getOneByOpenId($openid);

		if($third){
				return $third->user_id;
		} else {
			$userRepo = new UserRepo();
			$user = $userRepo->register($openid,$openid,$avatar_url,$nick_name);
			$info = $thirdRepo->create(['user_id'=>$user->id,'openid'=>$openid,'nick_name'=>$nick_name,'avatar_url'=>$avatar_url]);
			return  $user->id;
		}
	}
}